package com.sunmouse.toolkit.widget.canvas;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

import com.sunmouse.toolkit.R;

/**
 * Created by Administrator on 2017/10/16 0016.
 */
public class AvatarView extends View {

    private Paint mPaint;
    private int radius;
    private Bitmap mBitmap;

    public AvatarView(Context context) {
        this(context, null);
    }

    public AvatarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        radius = 100;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBitmap=loadMaterial(getResources().getDrawable(R.mipmap.avatar));
//        mPaint.setShader(new BitmapShader(loadMaterial(getResources().getDrawable(R.mipmap.ic_launcher)), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

//        canvas.drawCircle(getWidth()/2,getHeight()/2,radius,mPaint);
        canvas.drawBitmap(mBitmap,getWidth()/2-radius,getHeight()/2-radius,mPaint);
    }


    /**
     * load drawable
     *
     * @param drawable
     * @return
     */
    private Bitmap loadMaterial(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(radius * 2, radius * 2, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Path path=new Path();
        path.addCircle(radius,radius,radius, Path.Direction.CCW);
        canvas.clipPath(path);
        drawable.setBounds(0, 0, radius * 2, radius * 2);
        drawable.draw(canvas);
        return bitmap;
    }
}
